const express = require("express");
const app = express();
// 跨域
const cors = require("cors");
app.use(cors());
//解析表单数据
app.use(express.urlencoded({ extended: false }));
app.use(express.json());

// 导入 express-jwt 将JWT字符串解析还原成JSON对象(解析token)
const { expressjwt } = require("express-jwt");
const config = require("./config");
// 配置解析token的中间件
app.use(expressjwt({ secret: config.secretKey, algorithms: ["HS256"] }).unless({ path: [/^\/login\//, /^\/test/, /\//] }));
// 编写 出现错误的中间件(token验证错误的中间件)预防(token解析)错误导致服务器奔溃
app.use((err, req, res, next) => {
    // 捕获身份认证错误信息
    // if (err.name === "UnauthorizedError") return res.send("身份验证失败");
    // 出现其他错误
    res.send({ code: 500, err });
});

// 路由
let loginRouter = require("./router/loginRouter");
app.use("/login", loginRouter);
let backstageRouter = require("./router/backstageRouter");
app.use(backstageRouter);
let multer = require("./router/multer");
app.use(multer);
app.use("/imgs", express.static("./upload"));
let essay = require("./router/essayRouter");
app.use("/essay", essay);
let client = require("./router/clientRouter");
app.use(client);
let share = require("./router/shareRouter");
app.use(share);

app.listen(3000, () => {
    console.log("服务器启动成功");
    console.log("http://127.0.0.1:3000");
    console.log("http://localhost:3000");
    console.log("http://192.168.27.51:3000");
});
